<?php


namespace app\model;


use think\Model;

class UserModel extends Model
{
    protected $name = 'base_user';
    protected $pk = 'user_id';

    public function dept(){
        return $this->hasOne("DeptModel","dept_id","dept_id")->bind(['dept_name']);
//        return $this->hasOne("DeptModel","dept_id","dept_id");
    }

    public function position(){
        return $this->hasOne("PositionModel","position_id","position_id")->bind(['position_name']);
//        return $this->hasOne("PositionModel","position_id","position_id");
    }

    public function roles(){
        return $this->belongsToMany("RoleModel","base_user_role","role_id","user_id");
    }

    public function login($user_name,$user_pwd){
        $where['mobile|user_id'] = $user_name;
        $where['useable'] = 1;
        $user = $this->where($where)->find();
        if($user){
            if (md5($user_pwd) != $user->password) {
                return error(1, "密码错误");
            } else {
                $data = $this->info($user["user_id"]);
                return $data;
            }
        }
        else{
            return error(1, "用户不存在或被禁用");
        }
    }

    public function info($user_id){
//        $user = $this::with(['dept','position','role'])->find($user_id);
//        $user->visible([
//            'dept'=>['dept_id','dept_name'],
//            'position'=>['position_id','position_name'],
//            'role'=>['role_id','role_name']
//        ]);
//        $user->hidden(['dept_id','position_id','password']);
        $user = $this::with(['dept','position'])->find($user_id);
        if($user){
            $deptModel = new DeptModel();
            $topDept = $deptModel->getTopDept($user->dept_id);
            $user['company_name'] = $topDept->dept_full_name;
            $user['company_id'] = $topDept->dept_id;
            $user->hidden(['password']);
            $userInfo = $user->toArray();

            return $userInfo;
        }
        else{
            return error(1, "用户信息不存在");
        }
    }

}